<template>

  <el-input v-model="searchText" style="width: 240px;margin-left: 20px;margin-bottom: 30px" placeholder="请输入班级名" />
  <el-button style="margin-left: 20px;margin-bottom: 30px" type="primary" @click="searchClass()" round>搜索</el-button>
  <!-- 查看所有考试安排按钮 -->
  <el-button
      style="margin-left: 20px; margin-bottom: 30px"
      type="success"
      @click="openAllExamView"
      round
  >
    查看所有考试安排
  </el-button>

  <el-table :data="classTableData" stripe style="width: 100%" v-if="classTableData.length > 0">
    <el-table-column prop="name" label="班级名" wixdth="180" />
    <el-table-column prop="classCode" label="班级代码" wixdth="180" />
    <el-table-column prop="college" label="学院" wixdth="180" />
    <el-table-column prop="major" label="专业" wixdth="180" />
    <el-table-column prop="studentCount" label="人数" wixdth="180" />
    <el-table-column fixed="right" label="操作" min-width="180" align="center">
      <template #default="scope">
        <el-button link type="primary" @click="openCourseManaga(scope.row)">必修课程管理</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页条 -->
  <el-pagination
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      layout="prev, pager, next"
      @current-change="handlePageChange"
      style="margin-top: 20px; justify-content: center;"
      v-if="classTableData.length > 0"
  />
  <el-empty :image-size="200" v-else style="margin-top: 175px"/>

  <!-- 课程管理页面弹窗 -->
  <el-dialog v-model="ClassCourseManageVisible" title="课程管理" width="1800">
    <div>
      <!-- 学期选择下拉框 -->
      <div style="margin-bottom: 20px;">
        <span style="margin-right: 10px;">选择学期：</span>
        <el-select v-model="selectedSemester" placeholder="请选择学期" @change="handleSemesterChange">
          <el-option
              v-for="semester in semesterOptions"
              :key="semester"
              :label="semester"
              :value="semester"
          />
        </el-select>
      </div>

      <el-button style="margin-bottom: 20px; margin-right: 10px;" type="primary" plain @click="openAddCourseDialog"> 为当前学期添加/修改课程安排 </el-button>
      <el-button style="margin-bottom: 20px;" type="danger" plain @click="openDeleteCourseDialog"> 为当前学期删除课程安排 </el-button>

      <el-table :data="filteredCourseTableData" stripe style="width: 100%" v-if="filteredCourseTableData.length > 0">
        <el-table-column prop="name" label="课程名" width="260" />
        <el-table-column prop="courseCode" label="课程代码" wixdth="180" />
        <el-table-column prop="courseType" label="课程类型" wixdth="180" />
        <el-table-column prop="college" label="所属学院" wixdth="180" />
        <el-table-column prop="semester" label="开设学期" wixdth="180" />
        <el-table-column prop="credit" label="学分" width="100" />
        <el-table-column prop="classTime" label="开课时间" width="180" />
        <el-table-column prop="classLocation" label="开课地点" width="180" />
        <el-table-column prop="weekRange" label="开课周次" width="180" />
        <el-table-column fixed="right" label="操作" min-width="180" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="openExamManage(scope.row)">考试安排</el-button>
            <el-button link type="primary" @click="cancelExam(scope.row)"   :disabled="scope.row.isExamFinished">取消考试安排</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty :image-size="200" v-else style="margin-top: 50px"/>
    </div>
  </el-dialog>

  <!-- 添加课程对话框 -->
  <el-dialog v-model="addCourseDialogVisible" title=" 添加课程 " width="1000">
    <div>
      <el-table :data="availableCourses" stripe style="width: 100%" @selection-change="handleAddCourseSelection">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label=" 课程名 " width="260" />
        <el-table-column prop="courseCode" label=" 课程代码 " width="180" />
        <el-table-column prop="courseType" label=" 课程类型 " width="180" />
        <el-table-column prop="college" label=" 所属学院 " width="180" />
        <el-table-column prop="credit" label=" 学分 " width="100" />
      </el-table>
      <div style="text-align: center; margin-top: 20px;">
        <el-button type="primary" @click="submitAddCourses"> 添加 </el-button>
        <el-button @click="addCourseDialogVisible = false"> 取消 </el-button>
      </div>
    </div>
  </el-dialog>

  <!-- 删除课程对话框 -->
  <el-dialog v-model="deleteCourseDialogVisible" title=" 删除课程 " width="1000">
    <div>
      <el-table :data="filteredCourseTableData" stripe style="width: 100%"   @selection-change="handleDeleteCourseSelection">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label=" 课程名 " width="260" />
        <el-table-column prop="courseCode" label=" 课程代码 " width="180" />
        <el-table-column prop="courseType" label=" 课程类型 " width="180" />
        <el-table-column prop="college" label=" 所属学院 " width="180" />
        <el-table-column prop="credit" label=" 学分 " width="100" />
      </el-table>
      <div style="text-align: center; margin-top: 20px;">
        <el-button type="danger" @click="submitDeleteCourses"> 删除 </el-button>
        <el-button @click="deleteCourseDialogVisible = false"> 取消 </el-button>
      </div>
    </div>
  </el-dialog>

  <!-- 考试安排管理弹窗 -->
  <el-dialog v-model="examManageVisible" title="考试安排" width="600">
    <div>
      <el-form :model="examForm" :rules="examRules" ref="examFormRef" label-width="120px">
        <el-form-item label="课程代码" prop="courseCode">
          <el-input v-model="examForm.courseCode" disabled />
        </el-form-item>
        <el-form-item label="考试开始时间" prop="startTime">
          <el-date-picker
              v-model="examForm.startTime"
              type="datetime"
              placeholder="选择考试开始时间"
              value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"
              style="width: 100%"
              :disabled="examFormDisabled"
          />
        </el-form-item>
        <el-form-item label="考试结束时间" prop="endTime">
          <el-date-picker
              v-model="examForm.endTime"
              type="datetime"
              placeholder="选择考试结束时间"
              value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"
              style="width: 100%"
              :disabled="examFormDisabled"
          />
        </el-form-item>
        <el-form-item label="考试状态" prop="state">
          <el-select v-model="examForm.state" placeholder="请选择考试状态" style="width: 100%" :disabled="examFormDisabled">
            <el-option label="正常" :value="1" />
            <el-option label="取消" :value="0" />
            <el-option label="延迟" :value="2" />
            <el-option label="结束" :value="3" />
          </el-select>
        </el-form-item>
      </el-form>
      <div style="text-align: center; margin-top: 20px;">
        <el-button type="primary" @click="submitExam" :disabled="examFormDisabled">提交</el-button>
        <el-button @click="examManageVisible = false">取消</el-button>
      </div>
    </div>
  </el-dialog>

  <!-- 所有考试安排弹窗 -->
  <el-dialog v-model="allExamVisible" title="所有考试安排" width="1500">
    <div>
      <!-- 筛选条件 -->
      <div style="margin-bottom: 20px; display: flex; gap: 15px; flex-wrap: wrap;">
        <el-select v-model="filterParams.college" placeholder="选择学院" clearable @change="handleFilterChange">
          <el-option
              v-for="college in filterOptions.colleges"
              :key="college"
              :label="college"
              :value="college"
          />
        </el-select>

        <el-select v-model="filterParams.major" placeholder="选择专业" clearable @change="handleFilterChange">
          <el-option
              v-for="major in filterOptions.majors"
              :key="major"
              :label="major"
              :value="major"
          />
        </el-select>

        <el-select v-model="filterParams.semester" placeholder="选择学期" clearable @change="handleFilterChange">
          <el-option
              v-for="semester in filterOptions.semesters"
              :key="semester"
              :label="semester"
              :value="semester"
          />
        </el-select>

        <el-input
            v-model="filterParams.classCode"
            placeholder="输入班级代码"
            style="width: 200px"
            clearable
            @clear="handleFilterChange"
            @keyup.enter="handleFilterChange"
        />
      </div>

      <!-- 考试安排表格 -->
      <el-table :data="allExamData" stripe style="width: 100%">
        <el-table-column prop="courseName" label="课程名" width="300" />
        <el-table-column prop="courseCode" label="课程代码" width="130" />
        <el-table-column prop="college" label="学院" width="130" />
        <el-table-column prop="major" label="专业" width="130" />
        <el-table-column prop="className" label="班级" width="130" />
        <el-table-column prop="semester" label="学期" width="150" />
        <el-table-column prop="startTime" label="考试开始时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="考试结束时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="考试状态" width="120">
          <template #default="scope">
            <el-tag :type="getExamStateType(scope.row.state)">
              {{ getExamStateText(scope.row.state) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          :current-page="allExamCurrentPage"
          :page-size="allExamPageSize"
          :total="allExamTotal"
          layout="prev, pager, next"
          @current-change="handleAllExamPageChange"
          style="margin-top: 20px; justify-content: center;"
      />
    </div>
  </el-dialog>

</template>


<script lang="ts" setup>
import {onMounted, ref} from "vue";
import axios from '../utils/http.js';
import {ElMessage, ElPagination} from 'element-plus';

// 输入的搜索文字
const searchText = ref('');

//班级表格数据
const classTableData = ref([{
  name: '',
  classCode: '',
  college: '',
  major: '',
  studentCount: '',
  headTeacherName: ''
}])

//课程表格数据
const courseTableData = ref([{
  name: '',
  courseCode: '',
  courseType: '',
  college: '',
  semester: '',
  credit: '',
  classTime: '',
  classLocation: '',
  weekRange: ''
}])


//分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

//决定是否弹出班级增加学生页
const ClassCourseManageVisible = ref(false);

// 定义表单引用
const updateFormRef = ref(null)

// 验证规则
const rules = {
}

// 新增的响应式变量
const selectedSemester = ref('')
const semesterOptions = ref([])
const filteredCourseTableData = ref([])
const addCourseDialogVisible = ref(false)
const deleteCourseDialogVisible = ref(false)
const availableCourses = ref([])
const currentClassCode = ref('') // 存储当前操作的班级代码

// 表格选择相关
const addCourseSelection = ref([])
const deleteCourseSelection = ref([])

// 考试安排相关变量
const examManageVisible = ref(false)
const examFormRef = ref(null)
const examForm = ref({
  courseCode: '',
  startTime: '',
  endTime: '',
  state: 0
})

// 考试表单验证规则
const examRules = {
  startTime: [
    { required: true, message: '请选择考试开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择考试结束时间', trigger: 'change' }
  ],
  state: [
    { required: true, message: '请选择考试状态', trigger: 'change' }
  ]
}

// 所有考试安排相关变量
const allExamVisible = ref(false)
const allExamData = ref([])
const allExamCurrentPage = ref(1)
const allExamPageSize = ref(10)
const allExamTotal = ref(0)

// 筛选相关变量
const filterOptions = ref({
  colleges: [],
  majors: [],
  semesters: []
})

const filterParams = ref({
  college: '',
  major: '',
  semester: '',
  classCode: ''
})

/**
 * 初始化加载数据
 */
onMounted(() => {
  fetchData()
})

/**
 * 获取数据
 */
const fetchData = async () => {
  try {
    const response = await axios.get('/class/class', {
      params: {
        page: currentPage.value,
        size: pageSize.value
      }
    })
    console.log(response);
    classTableData.value = response.data.data;
    total.value = Number(response.data.message);
    console.log("Total:", total.value, "Type:", typeof total.value);
  } catch (error) {
    console.error('获取数据失败:', error);
  }
}

/**
 * 搜索班级
 */
const searchClass = async () => {
  if (searchText.value === '' || searchText.value.length <= 0) {
    fetchData();
    return;
  }
  try {
    const response = await axios.get('/class/class/search/' + searchText.value, {
      params: {
        page: currentPage.value,
        size: pageSize.value
      }
    })
    console.log(response);
    classTableData.value = response.data.data;
    total.value = Number(response.data.message);
    console.log("Total:", total.value, "Type:", typeof total.value);
  } catch (error) {
    console.error('获取数据失败:', error);
  }
}

/**
 * 页码变化处理
 * @param page
 */
const handlePageChange = (page) => {
  currentPage.value = page
  fetchData()
}

/**
 * 打开课程管理页面弹窗
 */
const openCourseManaga = async (row: any) => {
  currentClassCode.value = row.classCode

  try {
    // 生成学期选项
    generateSemesterOptions(row.classCode)

    // 获取当前班级已经选择的所有必修课
    const response = await axios.get("/cultivate/cultivate/class/" + row.classCode)
    console.log(response)
    if (response.data.code === 200) {
      courseTableData.value = response.data.data
      // 根据默认选中的学期过滤课程
      filterCoursesBySemester()
    } else {
      ElMessage.error("获取失败")
    }
  } catch (e) {
    ElMessage.error("获取失败：" + e)
  }

  ClassCourseManageVisible.value = true
}

/**
 * 生成学期选项
 */
const generateSemesterOptions = (classCode: string) => {
  const year = classCode.substring(0, 4) // 获取前4个字符作为年级
  const startYear = parseInt(year)

  semesterOptions.value = [
    `${startYear}年秋季学期`,
    `${startYear + 1}年春季学期`,
    `${startYear + 1}年秋季学期`,
    `${startYear + 2}年春季学期`,
    `${startYear + 2}年秋季学期`,
    `${startYear + 3}年春季学期`,
    `${startYear + 3}年秋季学期`,
    `${startYear + 4}年春季学期`
  ]

  // 默认选择第一个学期
  selectedSemester.value = semesterOptions.value[0]
}

/**
 * 学期变化处理
 */
const handleSemesterChange = () => {
  filterCoursesBySemester()
}

/**
 * 根据选中的学期过滤课程
 */
const filterCoursesBySemester = () => {
  if (!selectedSemester.value) {
    filteredCourseTableData.value = courseTableData.value
    return
  }

  filteredCourseTableData.value = courseTableData.value.filter(
      course => course.semester === selectedSemester.value
  )
}

/**
 * 打开添加课程对话框
 */
const openAddCourseDialog = async () => {
  try {
    // 调用后端接口获取可添加的课程列表
    const response = await axios.post('/cultivate/cultivate/available-courses',null, {
        params: {
          classCode: currentClassCode.value,
          semester: selectedSemester.value
        }
    })

    if (response.data.code === 200) {
      availableCourses.value = response.data.data
      addCourseDialogVisible.value = true
    } else {
      ElMessage.error("获取可添加课程失败")
    }
  } catch (e) {
    ElMessage.error("获取可添加课程失败：" + e)
  }
}

/**
 * 打开删除课程对话框
 */
const openDeleteCourseDialog = () => {
  deleteCourseDialogVisible.value = true
}

/**
 * 提交添加课程
 */
const submitAddCourses = async () => {
  if (addCourseSelection.value.length === 0) {
    ElMessage.warning("请选择要添加的课程")
    return
  }

  const courseCodes = addCourseSelection.value.map(course => course.courseCode).join(',')

  try {
    const response = await axios.post('/cultivate/cultivate/add-courses', null, {
      params: {
        classCode: currentClassCode.value,
        semester: selectedSemester.value,
        courseCodes: courseCodes
      }
    })

    if (response.data.code === 200) {
      ElMessage.success("添加课程成功")
      addCourseDialogVisible.value = false
      // 刷新课程数据
      await refreshCourseData()
    } else {
      ElMessage.error("添加课程失败")
    }
  } catch (e) {
    ElMessage.error("添加课程失败：" + e)
  }
}

/**
 * 提交删除课程
 */
const submitDeleteCourses = async () => {
  if (deleteCourseSelection.value.length === 0) {
    ElMessage.warning("请选择要删除的课程")
    return
  }

  const courseCodes = deleteCourseSelection.value.map(course => course.courseCode).join(',')

  try {
    const response = await axios.post('/cultivate/cultivate/delete-courses', null,{
      params: {
        classCode: currentClassCode.value,
        semester: selectedSemester.value,
        courseCodes: courseCodes
      }
    })

    if (response.data.code === 200) {
      ElMessage.success("删除课程成功")
      deleteCourseDialogVisible.value = false
      // 刷新课程数据
      await refreshCourseData()
    } else {
      ElMessage.error("删除课程失败")
    }
  } catch (e) {
    ElMessage.error("删除课程失败：" + e)
  }
}

/**
 * 刷新课程数据
 */
const refreshCourseData = async () => {
  try {
    const response = await axios.get("/cultivate/cultivate/class/" + currentClassCode.value)
    if (response.data.code === 200) {
      courseTableData.value = response.data.data

      // 为每个课程添加考试状态
      for (let course of courses) {
        course.isExamFinished = await checkExamFinished(course.courseCode)
      }

      courseTableData.value = courses

      filterCoursesBySemester()
    }
  } catch (e) {
    ElMessage.error("刷新课程数据失败：" + e)
  }
}

// 检查考试状态的独立方法
const checkExamFinished = async (courseCode) => {
  try {
    const response = await axios.get('/exam/exam/info', {
      params: { courseCode }
    })
    return response.data.code === 200 && response.data.data && response.data.data.state === 3
  } catch (e) {
    console.error("检查考试状态失败:", e)
    return false
  }
}

// 表格选择处理
const handleAddCourseSelection = (selection) => {
  addCourseSelection.value = selection
}

const handleDeleteCourseSelection = (selection) => {
  deleteCourseSelection.value = selection
}

// 新增一个响应式变量，用于控制表单是否禁用
const examFormDisabled = ref(false)

/**
 * 打开考试安排弹窗
 */
const openExamManage = async (row) => {
  try {
    // 设置课程代码
    examForm.value.courseCode = row.courseCode

    // 调用后端接口查询考试信息
    const response = await axios.get('/exam/exam/info', {
      params: {
        courseCode: row.courseCode
      }
    })

    if (response.data.code === 200 && response.data.data) {
      // 如果查询到考试信息，填充表单
      const examData = response.data.data
      examForm.value = {
        courseCode: examData.courseCode,
        startTime: examData.startTime,
        endTime: examData.endTime,
        state: examData.state
      }
      // 检查考试状态是否为3（已结束）
      examFormDisabled.value = examData.state === 3
    } else {
      // 没有查询到考试信息，重置表单（除了课程代码）
      examForm.value = {
        courseCode: row.courseCode,
        startTime: '',
        endTime: '',
        state: 0
      }
      // 没有考试安排时不禁用
      examFormDisabled.value = false
    }

    examManageVisible.value = true
  } catch (e) {
    ElMessage.error("获取考试信息失败：" + e)
    // 出错时也打开弹窗，但使用空表单
    examForm.value = {
      courseCode: row.courseCode,
      startTime: '',
      endTime: '',
      state: 0
    }
    examManageVisible.value = true
  }
}


/**
 * 提交考试安排
 */
const submitExam = async () => {
  // 表单验证
  if (!examFormRef.value) return

  try {
    await examFormRef.value.validate()
  } catch (e) {
    ElMessage.warning("请完善表单信息")
    return
  }

  // 验证时间逻辑：结束时间不能早于开始时间
  if (new Date(examForm.value.endTime) <= new Date(examForm.value.startTime)) {
    ElMessage.warning("考试结束时间不能早于或等于开始时间")
    return
  }

  try {
    const response = await axios.post('/exam/exam', examForm.value)

    if (response.data.code === 200) {
      ElMessage.success("考试安排保存成功")
      examManageVisible.value = false
    } else {
      ElMessage.error("考试安排保存失败")
    }
  } catch (e) {
    ElMessage.error("考试安排保存失败：" + e)
  }
}

/**
 * 取消考试安排
 */
const cancelExam = async (row) => {
  // 先检查考试状态
  if (await isExamFinished(row)) {
    ElMessage.warning("考试已结束，无法取消安排")
    return
  }

  // row.courseCode
  try {
    const response = await axios.delete("/exam/exam/" + row.courseCode);
    if (response.data.code === 200) {
      ElMessage.success("取消成功");
    } else {
      ElMessage.error("您未设置考试安排");
    }
  } catch (e) {
    ElMessage.error("取消失败:" + e);
  }
}

// 检查考试是否已结束
const isExamFinished = async (row) => {
  try {
    const response = await axios.get('/exam/exam/info', {
      params: {
        courseCode: row.courseCode
      }
    })

    if (response.data.code === 200 && response.data.data) {
      return response.data.data.state === 3
    }
    return false
  } catch (e) {
    console.error("检查考试状态失败:", e)
    return false
  }
}

/**
 * 打开所有考试安排弹窗
 */
const openAllExamView = async () => {
  allExamVisible.value = true
  await loadFilterOptions()
  await loadAllExamData()
}

/**
 * 加载筛选选项
 */
const loadFilterOptions = async () => {
  try {
    const response = await axios.get('/exam/exam/filter-options')

    console.log('筛选选项完整响应:', response.data)

    if (response.data.code === 200) {
      // 直接访问正确的数据结构路径
      filterOptions.value = response.data.data.data || {
        colleges: [],
        majors: [],
        semesters: []
      }

      console.log('设置后的筛选选项:', filterOptions.value)
    } else {
      ElMessage.error("获取筛选选项失败")
    }
  } catch (e) {
    console.error("加载筛选选项错误:", e)
    ElMessage.error("加载筛选选项失败：" + e)
  }
}

/**
 * 加载所有考试安排数据
 */
const loadAllExamData = async () => {
  try {
    const params = {
      page: allExamCurrentPage.value,
      size: allExamPageSize.value,
      ...filterParams.value
    }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await axios.get('/exam/exam/all', { params })
    if (response.data.code === 200) {
      allExamData.value = response.data.data
      allExamTotal.value = Number(response.data.message)
    }
  } catch (e) {
    ElMessage.error("加载考试安排失败：" + e)
  }
}

/**
 * 筛选条件变化处理
 */
const handleFilterChange = () => {
  allExamCurrentPage.value = 1
  loadAllExamData()
}

/**
 * 所有考试安排分页处理
 */
const handleAllExamPageChange = (page) => {
  allExamCurrentPage.value = page
  loadAllExamData()
}

/**
 * 格式化日期时间
 */
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN')
}

/**
 * 获取考试状态文本
 */
const getExamStateText = (state) => {
  const stateMap = {
    0: '取消',
    1: '正常',
    2: '延迟',
    3: '结束'
  }
  return stateMap[state] || '未知'
}

/**
 * 获取考试状态标签类型
 */
const getExamStateType = (state) => {
  const typeMap = {
    0: 'info',
    1: 'success',
    2: 'warning',
    3: 'primary'
  }
  return typeMap[state] || 'info'
}

</script>


<style scoped>
.upload-dropdown {
  padding: 10px;
}
.upload-dropdown :deep(.el-upload-list) {
  max-height: 150px;
  overflow-y: auto;
  margin-top: 10px;
}
</style>